package com.org.cloud.lg.filter;
import com.org.cloud.lg.property.PermitAllUrlProperties;
import com.org.cloud.lg.utils.ApiResult;
import com.org.cloud.lg.utils.Checker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Configuration
public class AccessGatewayFilter implements GlobalFilter {

    @Autowired
    PermitAllUrlProperties permitAllUrlProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request=exchange.getRequest();
        Route route =exchange.getRequiredAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        String requestURI = request.getPath().pathWithinApplication().value();
        ServerHttpRequest.Builder mutate = request.mutate();
        if(checkPmission(route,requestURI)){
            ServerHttpRequest build = mutate.build();
            return chain.filter(exchange.mutate().request(build).build());
        };
        //校验是否合法请求
        String token = request.getHeaders().getFirst("Authorization");
        if(checkJwtInvalid(token)){
            return setFailedRequest(exchange,ApiResult.result(-1,"无效的JWT"));
        }
        ServerHttpRequest build = mutate.build();
        //return exchange.getResponse().setComplete();
         return  chain.filter(exchange.mutate().request(build).build());
    }



//    private Mono<Void> getVoidMono(ServerWebExchange serverWebExchange, BaseResponse body) {
//        serverWebExchange.getResponse().setStatusCode(HttpStatus.OK);
//        byte[] bytes = JSONObject.toJSONString(body).getBytes(StandardCharsets.UTF_8);
//        DataBuffer buffer = serverWebExchange.getResponse().bufferFactory().wrap(bytes);
//        return serverWebExchange.getResponse().writeWith(Flux.just(buffer));
//    }

    /**
     * 网关抛异常
     *
     * @param body
     * @param code
     */
    private Mono<Void> setFailedRequest(ServerWebExchange serverWebExchange, ApiResult apiResult) {
        serverWebExchange.getResponse().setStatusCode(HttpStatus.OK);
        return serverWebExchange.getResponse().setComplete();
    }

    private boolean checkPmission(Route route,String api){
        return permitAllUrlProperties.ckTheSameApi(route.getId(),api);
    }

    private boolean checkJwtInvalid(String token){
       return Checker.BeBlank(token);
    }
}
